package com.app.controller.importExcel;

import com.app.common.SystemConstant;
import com.app.controller.UploadController;
import com.app.model.AdminUserModel;
import com.app.model.AttachmentModel;
import com.app.model.TestsLogModel;
import com.app.service.AdminUserService;
import com.app.service.AttachmentService;
import com.app.service.TestLogService;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.util.WordUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@Controller
@RequestMapping("/api/word")
public class ImportWord {
    @Autowired
    private TestLogService testLogService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    AttachmentService attachmentService;

    @PostMapping("/testLog")
    public Result<Object> testLog(@RequestBody TestsLogModel testsLogModel, HttpServletRequest request) throws Exception {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        testLogService.insert(testsLogModel);
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //这个map存的是ftl（word文件）里需要填入从数据库里查出来的字段部分
        //key是ftl文件里的${}部分，value是需要替换的数据
        //例如${student1Name},工具会去map里找key为student1Name的键值对，将其对应的值替换进去
        //获取当前系统支持的换行符
        String line = System.lineSeparator();
        StringBuilder res1 = new StringBuilder();
        StringBuilder res2 = new StringBuilder();
        StringBuilder res3 = new StringBuilder();
        for (char c : testsLogModel.getSubject().toCharArray()) {
            boolean carriageReturn = isCarriageReturn(c);
            if (carriageReturn) {
                res1.append("<w:br/>");
            } else {
                res1.append(c);
            }
        }
        testsLogModel.setSubject(res1.toString());
        for (char c : testsLogModel.getContent().toCharArray()) {
            boolean carriageReturn = isCarriageReturn(c);
            if (carriageReturn) {
                res2.append(line);
            } else {
                res2.append(c);
            }
        }
        testsLogModel.setContent(res2.toString());
        for (char c : testsLogModel.getNotes().toCharArray()) {
            boolean carriageReturn = isCarriageReturn(c);
            if (carriageReturn) {
                res3.append(line);
            } else {
                res3.append(c);
            }
        }
        testsLogModel.setNotes(res3.toString());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name", testsLogModel.getName());
        dataMap.put("modelCode", testsLogModel.getModelCode());
        dataMap.put("testTime", testsLogModel.getTestTime());
        dataMap.put("unit", testsLogModel.getUnit());
        dataMap.put("subject", testsLogModel.getSubject());
        dataMap.put("content", testsLogModel.getContent());
        dataMap.put("notes", testsLogModel.getNotes());
        dataMap.put("personnel", testsLogModel.getPersonnel());
        dataMap.put("compile", testsLogModel.getCompile());
        dataMap.put("organize", testsLogModel.getOrganize());
        //写出word文件
        WordUtils.generateWord(dataMap, "试验日志.ftl", SystemConstant.WORD_URL + sdf.format(d) + testsLogModel.getName() + "试验日志" + ".doc");
        File file = new File(SystemConstant.WORD_URL + sdf.format(d) + testsLogModel.getName() + ".doc");
        String filePath = SystemConstant.DEFAULT_PDF_SERVICE_URL + sdf.format(d) + testsLogModel.getName() + "试验日志" + ".doc";
        int lastIndexOf = file.getName().lastIndexOf(".");
        String suffix2 = file.getName().substring(lastIndexOf + 1);
        AttachmentModel attachmentModel = new AttachmentModel();
        attachmentModel.setName(file.getName());
        attachmentModel.setAttDir(filePath);
        attachmentModel.setAttType(suffix2);
        attachmentModel.setFileType(3);
        attachmentModel.setPid(testsLogModel.getPid());
        attachmentService.insert(attachmentModel);
        return Result.success(filePath);
    }

    public static boolean isCarriageReturn(char c) {
        return Character.getType(c) == Character.CONTROL;
    }
}
